package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BadcauseMapper;
import com.indusfo.spc.mapper.BadcauseTypeMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Badcause;
import com.indusfo.spc.pojo.BadcauseType;
import com.indusfo.spc.service.BadcauseService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: jpa05
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: BadcauseServiceImpl
 * @Author: Administrator
 * @Description: ${description}
 * @Date: 2019/8/12 14:27
 * @Version: 1.0
 */
@Service
public class BadcauseServiceImpl implements BadcauseService {

    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(BadcauseServiceImpl.class);

    @Resource
    private BadcauseMapper badcauseMapper;

    @Resource
    private BadcauseTypeMapper badcauseTypeMapper;

    @Resource
    private UploadMapper uploadMapper;
    //查询
    @Override
    public JSONObject listBadcause(Badcause badcause) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badcause.getPagesize();
            // 获取查询第几页
            Integer pageindex = badcause.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badcause.setIncept(pagesize * (pageindex - 1));
            }
            Integer BadcauseTypeId = null;
            if (badcause.getBadcauseTypeId() != null) {
            	BadcauseTypeId = badcause.getBadcauseTypeId();
            }
            //是否有类型
            System.out.println(BadcauseTypeId);
            //无类型查询第一个类型数据
//            if (BadcauseTypeId == null) {
//                //获取第一个数据
//                BadcauseType badcauseType = new BadcauseType();
//                badcauseType.setBadcauseTypePid(0);
//                List<BadcauseType> badcauseTypeList = badcauseTypeMapper.selectAllBadcauseType(badcauseType);
//                if (badcauseTypeList != null && badcauseTypeList.size() >= 1) {
//                    badcauseType = badcauseTypeList.get(0);
////                    blyy.setBlyytypeId(blyytype.getBlyytypeId());
//                }
////                blyytype.getBlyytypeId();
//                //生成树
//                List<XTreeNode> tree = new ArrayList<>();
//                List<XTreeNode> nodes = new ArrayList<>();
//                //查询全部
//                List<BadcauseType> list = badcauseTypeMapper.lookBadcauseType(new BadcauseType());
//                List<XTreeNode> treelist = new ArrayList<>();
//                //将树放入list
//                for (BadcauseType _MouldType : list) {
//                    XTreeNode node = new XTreeNode();
//                    node.setId(_MouldType.getBadcauseTypeId());
//                    node.setpId(_MouldType.getBadcauseTypePid());
//                    node.setTitle(_MouldType.getBadcauseTypeName());
//                    treelist.add(node);
//                }
//                System.out.println(badcauseType.getBadcauseTypeId());
//                XTreeUtil xTreeUtil = new XTreeUtil(badcauseType.getBadcauseTypeId(), treelist);
//                List<Integer> childs = new ArrayList<>();
//                List<Integer> parents = new ArrayList<>();
//                childs=xTreeUtil.getChilds();
//                parents=xTreeUtil.getParents();
////                List<Integer> ids=(List<Integer>)childs;
//                System.out.println(childs);
//                List<Badcause> listForPage = badcauseMapper.queryListBadcause(badcause, childs);
//                Integer count = badcauseMapper.countListBadcause(badcause, childs);
//                return JSONObject.oK(listForPage, count);
//            } else {
                if (BadcauseTypeId == null || BadcauseTypeId == 0) {
                    //全查
                    badcause.setBadcauseTypeId(null);
                    List<Badcause> listForPage = badcauseMapper.selectAllBadcause(badcause);
                    if (pagesize != null && pageindex != null) {
                        Integer count = badcauseMapper.countBadcause(badcause);
                        return JSONObject.oK(listForPage, count);
                    }else{
                        return JSONObject.oK(listForPage.get(0));
                    }
                } else {
                    List<XTreeNode> tree = null;
                    tree = new ArrayList<>();
                    List<XTreeNode> nodes = new ArrayList<>();
                    List<BadcauseType> list = badcauseTypeMapper.lookBadcauseType(new BadcauseType());
                    List<XTreeNode> treelist = new ArrayList<>();
                    for (BadcauseType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadcauseTypeId());
                        node.setpId(_MouldType.getBadcauseTypePid());
                        node.setTitle(_MouldType.getBadcauseTypeName());
                        treelist.add(node);
                    }
                    XTreeUtil xTreeUtil = new XTreeUtil(BadcauseTypeId, treelist);
                    List<Integer> childs = new ArrayList<>();
                    List<Integer> parents = new ArrayList<>();
                    childs=xTreeUtil.getChilds();
                    parents=xTreeUtil.getParents();
                    List<Badcause> listForPage = badcauseMapper.queryListBadcause(badcause, childs);
                    Integer count = badcauseMapper.countListBadcause(badcause, childs);
                    return JSONObject.oK(listForPage, count);
                }
//            }

            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法

//            if(blyytypeId==null){
//                BadcauseType blyytype = new BadcauseType();
//                blyytype.setBlyytypePid(0);
//                List<BadcauseType> blyytypeList = badcauseTypeMapper.selectAllBlyytype(blyytype);
//                if(blyytypeList != null && blyytypeList.size() >= 1){
//                    blyytype = blyytypeList.get(0);
//                    blyy.setBlyytypeId(blyytype.getBlyytypeId());
//                }
//            }else if(blyytypeId==0){
//                blyy.setBlyytypeId(null);
//            }
//            // 判断是否查询到数据
//            if (listForPage.isEmpty()) {
//                return JSONObject.oK("没有查询到数据",listForPage, 0);
//            }
            // 查询有多少条数据条数
//            return JSONObject.oK(listForPage.get(0));
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //新增
    @Override
    public JSONObject insertOrUpdateBadcause(Badcause badcause) {
        try {
            if (badcause.getBadcauseTypeId() == null) {
                badcause.setBadcauseTypeId(0);
            }
            if (badcause.getDataState() == null) {
                badcause.setDataState(1);
            }
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(badcause);
            if (checkParamsNotRepeatJson.isOk()) {
                if (badcause.getBadcauseId() != null) {// 有id,做更新
                    validate(badcause);
                    Integer row = badcauseMapper.updateByPrimaryKeySelective(badcause);
                    if (row == 0) {
                        throw new ModifyFailedException("编辑不良原因失败");
                    }
                    return JSONObject.oK("编辑成功", row);
                } else {// 没id,做新增
                    // 校验传入参数
                    validate(badcause);
                    Integer row = badcauseMapper.insertSelective(badcause);
                    if (row == 0) {
                        throw new ModifyFailedException("新增不良原因失败");
                    }
                    return JSONObject.oK("新增成功", row);
                }
            } else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    public JSONObject deleteBadcause(Long[] ids, Integer dataState) {
        try {
            //1.校验
            if (ids == null) {
                throw new ParamsErrorException("控制项目id不能为空");
            }
            if (dataState == null) {
                throw new ParamsErrorException("控制项目状态不能为空");
            }
            int row = badcauseMapper.deleteBadcause(ids, dataState);
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException(msg + "失败");
                    case 2:
                        throw new ModifyFailedException(msg + "失败");
                    case 3:
                        throw new ModifyFailedException(msg + "失败");
                }
            }
            return JSONObject.oK(msg + "成功", row);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //验证重复
    private JSONObject checkParamsNotRepeat(Badcause badcause) {
        try {
            // 判断不良原因类型ID是否传入
            if (badcause.getBadcauseTypeId() == null || badcause.getBadcauseTypeId() == 0) {
                throw new ParamsErrorException("未传入不良原因ID");
            } else {
                Badcause badcauseCheck = new Badcause();
                badcauseCheck.setBadcauseName(badcause.getBadcauseName());
                if (badcause.getBadcauseId() != null) {
                    // 剔除本条记录是否有重复
                	badcauseCheck.setBadcauseId(badcause.getBadcauseId());
                    int row = badcauseMapper.countParamsNotRepeat(badcauseCheck);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品");
                    }
                } else {
                    // 查询所有是否有重复
                    int row = badcauseMapper.countParamsNotRepeat(badcauseCheck);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品");
                    }
                }
                return JSONObject.oK();
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //非空判断
    private void validate(Badcause badcause) {
        //不良原因id
        Integer badcauseId = badcause.getBadcauseId();
        //不良原因名称
        String badcauseName = badcause.getBadcauseName();
        //不良原因类型id
        Integer badcauseTypeId = badcause.getBadcauseTypeId();
        //不良原因名称
        String remark = badcause.getRemark();
        if (StringUtils.isEmpty(badcauseName)) {
            throw new ParamsErrorException("不良原因名称不能为空");
        }
        if (badcauseName.getBytes().length > 50) {
            throw new ParamsErrorException("不良原因名过长");
        }
        if (remark != null) {
            if (remark.getBytes().length > 100) {
                throw new ParamsErrorException("说明过长");
            }
        }
        if (badcauseTypeId == null) {
            throw new ParamsErrorException("不良原因类型不能为空");
        }
//        if(typeId==null) {
//            throw new ParamsErrorException("不良原因类型id不能为空");
//        }
    }

    @Override
    public String checkNoRepeat(Badcause badcause) {
        //不良原因名称
        String badcauseName = badcause.getBadcauseName();
        //不良原因类别名称
        String badcauseTypeName = badcause.getBadcauseTypeName();
        if(StringUtils.isBlank(badcauseName) && StringUtils.isBlank(badcauseTypeName)){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if (StringUtils.isEmpty(badcauseName)) {
            return "不良原因名称为空";
        }
        // 查询是否有重复
        int row = badcauseMapper.countParamsNotRepeat(badcause);
        if (row > 0) {
            return "不良原因名称已存在";
        }
        if (badcauseName.getBytes().length > 50) {
            return "不良原因名过长,长度不能超过50";
        }
        if (StringUtils.isEmpty(badcauseTypeName)) {
            return "不良原因类别名称为空";
        }
		
		Map<String, BadcauseType> badcauseTypeMap = uploadMapper.queryDefectType();
		if(!badcauseTypeMap.containsKey(badcauseTypeName)){
		    return "不良原因类别名称填写错误/不规范";
		}
        BadcauseType badcauseType = badcauseTypeMap.get(badcauseTypeName);
        badcause.setBadcauseTypeId(badcauseType.getBadcauseTypeId()); 
        return null;
    }

    @Override
    public JSONObject updateListBadcause(List<Badcause> badcauseList) {
		  int flag = uploadMapper.updateListBadcause(badcauseList); if(flag>0){ return
		  JSONObject.oK("新增成功"); }
        return JSONObject.oK("新增失败");
    }
}
